package com.ruoyi.domain.base;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.exception.InvoiceApiException;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
public class PageDomain<T> {

    private Integer total;

    private Integer totalPage;

    private List<T> data;

    public static <T> PageDomain build(Integer page, Integer rows, List<T> data){
        if(data == null || data.size()==0){
            return new PageDomain(0,0,new ArrayList());
        }
        int totalPage = PageUtil.totalPage(data.size(), rows);
        int[] startEnd = PageUtil.transToStartEnd(page-1, rows);
        if(page>totalPage){
            InvoiceApiException.createAndThrowIt(StrUtil.format("页数过长,总页数:{},查询页数:{}",totalPage,page));
        }
        return new PageDomain(data.size(),totalPage,data.subList(startEnd[0],page == totalPage ? data.size() :startEnd[1]));
    }

}
